import { useState, useEffect } from 'react';

export interface ViewportInfo {
  width: number;
  height: number;
  scale: number;
  scrollY: number;
  scrollX: number;
  isScrolling: boolean;
}

/**
 * useViewport Hook
 * 返回视口尺寸、缩放信息和滚动状态
 *
 * @returns ViewportInfo 对象包含视口的详细信息
 *
 * 性能优化：
 * - resize 和 scroll 事件使用防抖
 * - 滚动状态检测自动超时
 */
export const useViewport = (): ViewportInfo => {
  const [viewportInfo, setViewportInfo] = useState<ViewportInfo>(() => {
    if (typeof window === 'undefined') {
      return {
        width: 1024,
        height: 768,
        scale: 1,
        scrollY: 0,
        scrollX: 0,
        isScrolling: false
      };
    }

    return {
      width: window.innerWidth,
      height: window.innerHeight,
      scale: window.visualViewport?.scale || 1,
      scrollY: window.scrollY || window.pageYOffset,
      scrollX: window.scrollX || window.pageXOffset,
      isScrolling: false
    };
  });

  useEffect(() => {
    if (typeof window === 'undefined') return;

    let resizeTimeoutId: NodeJS.Timeout;
    let scrollTimeoutId: NodeJS.Timeout;
    let scrollEndTimeoutId: NodeJS.Timeout;

    // 更新视口信息
    const updateViewport = () => {
      setViewportInfo({
        width: window.innerWidth,
        height: window.innerHeight,
        scale: window.visualViewport?.scale || 1,
        scrollY: window.scrollY || window.pageYOffset,
        scrollX: window.scrollX || window.pageXOffset,
        isScrolling: viewportInfo.isScrolling
      });
    };

    // Resize 处理（防抖 300ms）
    const handleResize = () => {
      clearTimeout(resizeTimeoutId);
      resizeTimeoutId = setTimeout(updateViewport, 300);
    };

    // Scroll 处理（防抖 100ms，响应更快）
    const handleScroll = () => {
      clearTimeout(scrollTimeoutId);
      clearTimeout(scrollEndTimeoutId);

      // 立即设置 isScrolling 为 true
      setViewportInfo(prev => ({
        ...prev,
        scrollY: window.scrollY || window.pageYOffset,
        scrollX: window.scrollX || window.pageXOffset,
        isScrolling: true
      }));

      // 防抖更新完整信息
      scrollTimeoutId = setTimeout(() => {
        updateViewport();
      }, 100);

      // 150ms 后设置 isScrolling 为 false
      scrollEndTimeoutId = setTimeout(() => {
        setViewportInfo(prev => ({
          ...prev,
          isScrolling: false
        }));
      }, 150);
    };

    // Visual Viewport API 处理（支持移动端缩放）
    const handleVisualViewportResize = () => {
      setViewportInfo(prev => ({
        ...prev,
        scale: window.visualViewport?.scale || 1
      }));
    };

    window.addEventListener('resize', handleResize);
    window.addEventListener('scroll', handleScroll, { passive: true });

    if (window.visualViewport) {
      window.visualViewport.addEventListener('resize', handleVisualViewportResize);
    }

    return () => {
      clearTimeout(resizeTimeoutId);
      clearTimeout(scrollTimeoutId);
      clearTimeout(scrollEndTimeoutId);

      window.removeEventListener('resize', handleResize);
      window.removeEventListener('scroll', handleScroll);

      if (window.visualViewport) {
        window.visualViewport.removeEventListener('resize', handleVisualViewportResize);
      }
    };
  }, []);

  return viewportInfo;
};
